<template>
	<om-page title="登录">
		<view class="padding-xl text-center text-xxl bg-steelblue">欢迎登录OM系统</view>
		<view class="content padding-top">
			<uni-list title="">
				<uni-list-item :showArrow="false">
					<view class="tui-flex">
						<view class="tui-col-4"><om-label label="组织" required></om-label></view>
						<view class="tui-left tui-col-8">
							<picker @change="bindOrgChange" mode="selector" :value="orgIndex" :range="orgSelectList" range-key="orgname">
								<view class="tui-right">{{ getOrgName || '请选择' }}</view>
							</picker>
						</view>
					</view>
				</uni-list-item>
			</uni-list>
			<view class="btn-row"><button type="primary" class="primary" @tap="autoLogin">登录</button></view>
		</view>
	</om-page>
</template>

<script>
import { mapState, mapActions } from 'pinia';
import { useLoginUserStore } from '@/stores/login-user.js'
export default {
	data() {
		return {
			login_org: 'OM系统',
			orgIndex: 0,
			orgSelectList: []
		};
	},
	computed: {
		...mapState(useLoginUserStore,['orgList']),
		getOrgName() {
			if (this.orgSelectList.length) {
				let org = this.orgSelectList[this.orgIndex]
				this.setSubUrl(this.orgList[org.orgCode].om_url)
				this.setUserId(org.userid)
				this.setOrgCode(org.orgCode)
				return org.orgname;
			}
			return '';
		}
	},
	methods: {
		...mapActions(useLoginUserStore,[
			'login',
			'setOrgName',
			// #ifdef MP-WEIXIN
			'setOrgCode',
			'setOrgList',
			'setSubUrl',
			'setOpenid',
			'setUserId'
			// #endif
		]),
		bindOrgChange(e) {
			this.orgIndex = e.target.value;
		},
		autoLogin() {
			let _that = this;
			wx.login({
				success(res) {
					if (res.code) {
						_that.requestLogin(res.code);
					} else {
						console.log('登录失败！' + res.errMsg);
					}
				},
				fail: function() {}
			});
		},
		requestLogin(code) {
			let _that = this;
			_that.om
				.request(
					'wxlogin/doLogin',
					{
						code: code
					},
					'post'
				)
				.then(res => {
					_that.dbVerify(res);
				});
		},
		dbVerify(d) {
			let _that = this;
			if (d.succeed) {
				var response = d.value;
				_that.login(response);
				uni.switchTab({
					url: '/pages/main/main/main'
				});
			} else {
				_that.om.toast(d.msg);
			}
		}
	},
	onLoad(options) {
		let _that = this;
		uni.getStorage({
			key: 'orges',
			success: function(res) {
				if (res.data && res.data.length) {
					_that.orgSelectList = res.data;
				}
			}
		});
	}
};
</script>

<style></style>
